package ${servicePackageName}.service.sys.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ${commonPackageName}.constant.Constant;
import ${commonPackageName}.enums.ExceptionEnum;
import ${commonPackageName}.exception.BusinessException;
import ${commonPackageName}.utils.AssertUtil;
import ${servicePackageName}.entity.sys.SysUser;
import ${servicePackageName}.entity.sys.SysUserDepartment;
import ${servicePackageName}.entity.sys.SysUserRole;
import ${servicePackageName}.mapper.sys.SysUserMapper;
import ${servicePackageName}.qo.other.BatchDeleteQo;
import ${servicePackageName}.qo.sys.UserListPageReq;
import ${servicePackageName}.qo.sys.UserReq;
import ${servicePackageName}.service.sys.ISysUserDepartmentService;
import ${servicePackageName}.service.sys.ISysUserRoleService;
import ${servicePackageName}.service.sys.ISysUserService;
import ${servicePackageName}.vo.sys.UserListPageVo;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lizihao
 * @since 2020-11-18
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
	@Autowired
	private ISysUserRoleService iSysUserRoleService;
	@Autowired
	private ISysUserDepartmentService iSysUserDepartmentService;
	
	/**
	 * 用户列表分页查询
	 * @DS("slave_1")
	 */
	@Override
	public Page<UserListPageVo> getUserListPage(IPage<UserListPageVo> page, UserListPageReq userListPageReq) {
		return this.baseMapper.getUserListPage(page, userListPageReq);
	}
	/**
	 * 获取用户信息
	 * @DS("slave")
	 */
	@Override
	public UserListPageVo getUserInfo(Long userId) {
		UserListPageVo dto = this.baseMapper.getUserInfo(userId);
		if(!StrUtil.isBlank(dto.getRoleIdStr())) {
			dto.setRoleId(Convert.toStrArray(dto.getRoleIdStr().split(",")));
		}
		return dto;
	}
	/**
	 * 修改或新增用户
	 */
	@Override
	@DS("master")
	@Transactional(rollbackFor = Exception.class)
	public void saveOrUpdateUser(UserReq userReq) throws Exception {
		if(null == userReq.getId()) {
			//判断是否有重复账号
			QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
	        queryWrapper.eq("user_account", userReq.getUserAccount());
	        SysUser check = this.baseMapper.selectOne(queryWrapper);
	        AssertUtil.isNotNull(check, () -> new BusinessException(ExceptionEnum.ACCOUNT_IS_EXIST));
			//密码盐
			String salt = RandomUtil.randomString(6);
			//默认密码123456
			SysUser u = new SysUser()
			.setUserAccount(userReq.getUserAccount())
			.setUserName(userReq.getUserName())
			.setUserPassword(SecureUtil.md5(Constant.DEFAULT_PASSWORD.concat(salt)))
			.setUserSalt(salt);
			this.baseMapper.insert(u);
			//再授权角色 
			if(null != userReq.getRoleId()) {
				if(userReq.getRoleId().length > 0) {
					for(String roleId : userReq.getRoleId()) {
						SysUserRole userRole = new SysUserRole()
								.setRoleId(Long.valueOf(roleId))
								.setUserId(u.getId());
						iSysUserRoleService.save(userRole);
					}
				}
			}
			//绑定机构关系
			if(!StrUtil.isBlank(userReq.getDepartmentId())) {
				String []depIds = userReq.getDepartmentId().split(",");
				for(String s : depIds) {
					SysUserDepartment depUser = new SysUserDepartment();
			        depUser.setDepartmentId(Long.valueOf(s));
			        depUser.setUserId(u.getId());
			        iSysUserDepartmentService.save(depUser);
				}
			}
		}else {
			//更新
			SysUser u = new SysUser();
			u.setUserName(userReq.getUserName());
			u.setId(Long.valueOf(userReq.getId()));
			u.setIsEnable(userReq.getIsEnable());
			this.baseMapper.updateById(u);
			//删除角色再重新授权
			QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
	        queryWrapper.eq("user_id", userReq.getId());
	        iSysUserRoleService.remove(queryWrapper);
	        if(userReq.getRoleId().length > 0) {
				for(String roleId : userReq.getRoleId()) {
					SysUserRole userRole = new SysUserRole()
							.setRoleId(Long.valueOf(roleId))
							.setUserId(u.getId());
					iSysUserRoleService.save(userRole);
				}
			}
			//删除机构再重新添加
			QueryWrapper<SysUserDepartment> queryWrapper2 = new QueryWrapper<>();
	        queryWrapper2.eq("user_id", u.getId());
	        iSysUserDepartmentService. remove(queryWrapper2);
	        if(!StrUtil.isBlank(userReq.getDepartmentId())) {
				String []depIds = userReq.getDepartmentId().split(",");
				for(String s : depIds) {
					SysUserDepartment depUser = new SysUserDepartment();
			        depUser.setDepartmentId(Long.valueOf(s));
			        depUser.setUserId(u.getId());
			        iSysUserDepartmentService.save(depUser);
				}
			}
		}
	}
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(BatchDeleteQo qo) {
		qo.getIds().forEach(a ->{
			SysUser u = new SysUser();
			u.setId(Long.valueOf(a));
			u.setIsDelete(1);
			this.baseMapper.updateById(u);
		});
	}
}
